<?php
/**
 * Created by PhpStorm.
 * User: minicart
 * Date: 2018/9/21
 * Time: 21:22
 */
namespace app\admin\controller;
use app\admin\service\AdministrationService;
use app\admin\service\CommonService;
use app\models\AuditionModel;
use app\models\CampusModel;
use app\models\CourseModel;
use app\models\DictionaryModel;
use app\models\FollowUpLogModel;
use app\models\GradesDetailsListsModel;
use app\models\StudentModel;
use app\models\StudentSubjectClassModel;
use app\models\StudentSubjectInfosClassModel;
use app\models\UserModel;

/**
 * Class Customer
 * @package app\admin\controller
 */
class Administration extends Common
{

    /**
     * 试听管理模型.
     *
     * @var AuditionModel
     */
    protected $auditionModel;

    /**
     * 学员模型.
     *
     * @var StudentModel
     */
    protected $studentModel;

    /**
     * 用户模型.
     *
     * @var UserModel
     */
    protected $userModel;

    /**
     * 沟通记录模型.
     *
     * @var FollowUpLogModel
     */
    protected $followUpLogModel;

    /**
     * 沟通记录管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function customer_follow_up_list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['is_audition'] = 2;
            $followUpLog = $this->followUpLogModel->getCustomerFollowUpLists($param);

            $this->success('success', '', $followUpLog, 0);
        }

        $campus = CampusModel::all(['status'=>1]);
        $this->dictionary();
        return $this->fetch('', [
            'campus' => $campus
        ]);
    }

    /**
     * 选择到访（签到）日期
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function time_date(){
        if ($this->request->isAjax()) {
            $data = input('post.');
			$data_['visiting_datetime']  =  strtotime($data['date_num'].' '.$data['time_num']);
            $res = $this->studentModel->where(['id' => $data['student_id']])->update(['visiting_datetime' => $data_['visiting_datetime'],'follow_up'=>103]);
            if(!$res){
                $this->error('设置到访时间失败', null, '', 1);
            }
            $this->success('设置到访时间成功', '', $data, 1);
        }
        $student_id = input('student_id'); //学生ID
        return $this->fetch('',['student_id' => $student_id]);

    }


    /**
     * 上门管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function appointment_manage()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $course = $this->studentModel->getAppointmentManageStudentLists($param);
            $this->success('success', '', $course, 0);
        }
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
        $users = $this->userModel->where($where)->field('id,name')->select()->toArray();
        $arr[] = [
            'id' => 0,
            'name' => '公海',
        ];
        $users = array_merge($users, $arr);
        $this->dictionary();
        return $this->fetch('', [
            'users' => $users,
        ]);
    }

    /**
     * 试听课管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function audition_order_list()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            /*
            $param['is_audition'] = 0;
            $course = $this->studentModel->getStudentLists($param);
            */
            if(get_current_type() == 5){  //员工
                $param['user_id'] = get_current_id();
            }

            $audition_student = $this->auditionModel->getAuditionLists($param);
            $this->success('success', '', $audition_student, 0);
        }
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
        $users = $this->userModel->where($where)->field('id,name')->select()->toArray();
        $arr[] = [
            'id' => 0,
            'name' => '公海',
        ];
        $users = array_merge($users, $arr);
        $this->dictionary();
        return $this->fetch('', [
            'users' => $users,
        ]);
    }

    /**
     * 试听课管理签到
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function audition_check_status(){
        if ($this->request->isAjax()) {
            $data = input('post.');
            $id = $data['id'];
            $status = $data['status'];
            if ($status == 0) {
                $msg = '未签';
            } else {
                $msg = '已签';
            }
            $res = $this->auditionModel->get(['id' => $id]);
            if($res['status'] == 0){
                $this->success('所选数据中已存在无效数据,请重新选择', '', '', 1);
            }

            if(!$this->auditionModel->save(['sign_status' => $status],['id' => $id])){
                $this->error('签到失败', null, '', 1);
            }

            $count = $this->auditionModel->where(['student_id' => $res['student_id'], 'sign_status' => 1])->count();
            if($count > 0){
                $this->studentModel->where(['id' => $res['student_id']])->update(['follow_up' => 103]); //已上门
            }else{
                $this->studentModel->where(['id' => $res['student_id']])->update(['follow_up' => 35]); //已跟进
            }

            $this->success($msg, '', $data, 1);
        }
    }

    /**
     * 转介绍管理
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function customer_new_introduce()
    {
        if ($this->request->isAjax()) {
            $param = $this->request->param();
            $param['is_audition'] = ['in','1,2'];
            $param['introduction'] = ['gt',0];
            $course = $this->studentModel->getStudentLists($param);

            $this->success('success', '', $course, 0);
        }
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){/*校区数据权限*/
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){/*区域数据权限*/
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
		$users = $this->userModel->where($where)->field('id,name')->select()->toArray();
		$arr[] = [
			'id' => 0,
			'name' => '公海',
		];
		$users = array_merge($users, $arr);
		$this->dictionary();
		return $this->fetch('', [
			'users' => $users,
		]);
    }

	/**
	 * 取消预约.
	 *
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function cancel_reservation()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$where['id'] = ['in', $data['ids']];;
			$arr = explode(',',$data['ids']);
			$res = $this->studentModel->save(['follow_up' => 35,'next_drop_in_date'=> null, 'visiting_date'=> '--'], $where);
			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				CommonService::writeFollowUpLog($id, $data['campus_id'],1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.'取消预约', 1,$student['follow_up']);
			}
			if (false === $res) {
				$this->error('操作失败', null, '', 2);
			}
			$this->success('操作成功', null, '', 1);
		}

	}

	/**
	 * 取消预约-试听
	 */
	public function audition_cancel_reservation()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$where['id'] = ['in', input('ids')];

			//删除课节详情数据
			$ids_arr = explode(',',input('ids'));
			for ($i=0; $i < count($ids_arr); $i ++){
				$res = AuditionModel::get(['id' => $ids_arr[$i]]);
				(new StudentSubjectInfosClassModel())->where(['class_manage_details_id' => $res['class_id'], 'student_id' => $res['student_id'], 'contract_number' => '---'])->delete();
			}

			//删除班级学生数据
			for ($i=0; $i < count($ids_arr); $i ++){
				$res = AuditionModel::get(['id' => $ids_arr[$i]]);
				$grades_res = (new GradesDetailsListsModel())->get(['id' => $res['class_id']]);
				$count = (new StudentSubjectInfosClassModel())->where(['class_subject_id' => $grades_res['class_manage_id'], 'student_id' => $res['student_id'], 'contract_number' => '---'])->count();
				if($count <= 0){
					(new StudentSubjectClassModel())->where(['class_subject_id' => $grades_res['class_manage_id'], 'student_id' => $res['student_id'], 'student_type' => 4])->delete();
				}
			}

			//更新客户跟进状态
			$res_student_id = $this->auditionModel->where($where)->group('student_id')->column('student_id');
			$student_id_arr = $res_student_id;
			$res = $this->auditionModel->where($where)->delete();

			$res_student_id_arr = implode(',',$res_student_id);
			$count = $this->auditionModel->where(['student_id' => ['in',$res_student_id_arr]])->count();
			if($count <= 0){
				$this->studentModel->where(['id' => ['in',$res_student_id_arr]])->update(['follow_up' => 35]);  //转为跟进状态
			}

			for($k=0; $k < count($student_id_arr); $k ++){
				$count = $this->auditionModel->where(['student_id' => $student_id_arr[$k], 'sign_status' => 1])->count();
				if($count <= 0){
					$this->studentModel->where(['id' => $student_id_arr[$k]])->update(['follow_up' => 35]);  //转为跟进状态
				}
			}

			if (false === $res) {
				$this->error('移除失败', null, '', 2);
			}
			$this->success('移除成功', null, '', 1);
		}
	}

	/**
	 * 将客户标记为无效.
	 *
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function invalid()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$where['id'] = ['in', input('ids')];

			$arr = explode(',', input('ids'));
			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				if($student['is_audition'] == 2){
					$this->error($student['name'].'为正式学员,无法转为无效客户', null, '', 2);
				}
			}

			$this->auditionModel->save(['status' => 0], ['student_id' => ['in', input('ids')]]);  //试听记录转为无效
			//follow_up:33 未分配
			$res = $this->studentModel->save(['follow_up' => 33,  'course_consultant_type' => 0, 'course_consultant' => '-', 'status' => 2, 'reason' => input('reason'), 'user_id' => 0], $where);

			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				CommonService::writeFollowUpLog($id, $student['campus_id'],1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.'的状态修改为无效'.'<br/>'.'标记原因：'.input('reason'), 1,$student['follow_up']);
			}
			if (false === $res) {
				$this->error('标记失败', null, '', 2);
			}
			$this->success('标记成功', null, '', 1);
		}

		return $this->fetch('', [
			'ids' => input('ids'),
			'campus_id' => input('campus_id')
		]);
	}

	/**
	 * 将客户转给同事.
	 *
	 * @throws \think\exception\DbException
	 *
	 * @return mixed
	 */
	public function assignment()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$data = input('post.');
			$where['id'] = ['in', input('ids')];
			$arr = explode(',', input('ids'));
			$data['name'] = $this->userModel->get(['id' => $data['user_id']])['name'];
			$res = $this->studentModel->save(['course_consultant_type' => 1,'campus_id' => input('campus_id'),  'user_id' => $data['user_id'], 'course_consultant' => $data['name']], $where);
			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				CommonService::writeFollowUpLog($id, input('campus_id'),1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.'转给了同事'.' '.$data['name'], 1,$student['follow_up']);
			}
			if (false === $res) {
				$this->error('操作失败', null, '', 2);
			}
			$this->success('操作成功', null, '', 1);
		}

		$where = [];
		$type = 0;
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['id'] = get_current_campus_id();
			$type = 1;
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
		$campus = (new CampusModel())->where($where)->select();

		return $this->fetch('', [
			'type' => $type,
			'ids' => input('ids'),
			'status' => input('status'),
			'campus' => $campus,
			'campus_id' => input('campus_id')
		]);
	}

	/**
	 * 将客户转为正式学员.
	 *
	 * @throws \think\exception\DbException
	 */
	public function formal_student()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$where['id'] = ['in', input('ids')];
			$info = '转为正式学员';
			$arr = explode(',', input('ids'));
			$res = $this->studentModel->save(['is_audition' => 2, 'course_consultant_type' => 1, 'course_consultant' => get_current_name(), 'user_id' => get_current_id()], $where);
			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				CommonService::writeFollowUpLog($id, input('campus_id'),1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.$info, 1,$student['follow_up']);
			}
			if (false === $res) {
				$this->error('操作失败', null, '', 2);
			}
			$this->success('操作成功', null, '', 1);
		}
		$ids = explode(',',input('ids'));
		$count = count($ids);
		return $this->fetch('', [
			'ids' => input('ids'),
			'count'=>$count,
			'type' => input('type'),
			'campus_id' => input('campus_id')
		]);
	}

	/**
	 * 将客户转为试听学员
	 *
	 * @throws \think\exception\DbException
	 */
	public function audition()
	{
		if ($this->request->isAjax() && $this->request->isPost()) {
			$where['id'] = ['in', input('ids')];
			$info = '转为试听学员';
			$course = (new CourseModel())->get(input('course'));
			$arr = explode(',', input('ids'));
			$res = $this->studentModel->save(['intentional_course'=>$course['course_name'],'is_audition' => 0, 'course_consultant_type' => 1, 'course_consultant' => get_current_name(), 'user_id' => get_current_id()], $where);
			foreach ($arr as $id) {
				// 学员客户跟进沟通记录写入
				$student = StudentModel::get($id);
				CommonService::writeFollowUpLog($id, input('campus_id'),1, get_current_name().' '.'将客户'.' '.$student['student_name'].' '.$info.'且试听课程为:'.$course['course_name'], 1,$student['follow_up']);
			}
			if (false === $res) {
				$this->error('操作失败', null, '', 2);
			}
			$this->success('操作成功', null, '', 1);
		}
		$where = [];
		if(get_current_type() == 4 || get_current_type() == 5){
			$where['campus_id'] = get_current_campus_id();
		}elseif (get_current_type() == 2 || get_current_type() == 3){
			$where['campus_id'] = ['in',get_current_campus_id()];
		}
		$where['status'] = 1;
		$course = (new CourseModel())->where($where)->select();
		return $this->fetch('', [
			'ids' => input('ids'),
			'course'=>$course,
			'campus_id' => input('campus_id')
		]);
	}

    /**
     * 实例化.
     *
     * @return bool|void
     */
    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->studentModel = new StudentModel();
        $this->followUpLogModel = new FollowUpLogModel();
        $this->userModel = new UserModel();
        $this->auditionModel = new AuditionModel();
    }
}